﻿$.hasPermission('CMSPage.Edit', cmsPageVersion.json_PageId, function(r) {

    if (!r) {
        return;
    }

    // Setup editor container

    $('#cmsEditor').remove();
    $('#cmsEditorDummy').remove();
    var editor = $('<div id="cmsEditor"></div>');
    var editorDummy = $('<div id="cmsEditorDummy"></div>');

    $('body').prepend(editor);
    $('body').prepend(editorDummy);
    editor.scrollFollow({ speed: 250 });

    editor.setTemplateURL('/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Templates.CMSEditor.tpl').processTemplate({});
    editor.find('li').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });
    editor.width($(window).width());

    // Escape closes any modals

    $(document).keyup(function(event) {
        if (event.keyCode == 27) {
            $.modal.close();
        }
        return true;
    });

    // Page Versions

    $.hasPermission('CMSPage.Approve', cmsPageVersion.json_PageId, function(r) {
        $('#cmsPageVersionLink').hover(function() {
            $('#cmsPageVersionLinkHover').show(0);
        }, function() {
            $('#cmsPageVersionLinkHover').hide(0);
        });

        $('#cmsPublish').click(function() {
            $('#cmsPublish img:first')[0].src = '/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_loading.gif';
            $('#cmsPublish h3:first').html('Saving...');
            $('#cmsPublish h4:first').html('');

            $('#cmsPageVersionLink img:first')[0].src = '/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_loading.gif';
            $('#cmsPageVersionLink h3:first').html('Publishing...');
            $('#cmsPageVersionLink h4:first').html('Please wait');
            $.postJSON('/cms/pages/makeLive/' + cmsPageVersion.json_PageId, { version: cmsPageVersion.json_PageVersionId }, function(response) {
                cmsPageVersionCheck();
            });
        });

        $('#cmsVersions').click(function() {
            $.modal.close();
            $('#cmsPageVersionManagerContainer').cmsPageVersionManager({});
        });
    });

    cmsPageVersionChecker();

    // Page Info

    $('#cmsPageInfo').hide(0);
    $('#cmsPageInfoLink').click(function() {
        $.modal.close();
        $('#cmsPageInfo').cmsPageInfo({});
    });

    // Pages

    $('#cmsPagesLink').click(function() {
        $.modal.close();
        $('#cmsPageManagerContainer').modal();
        $('#cmsPageManager').cmsPageManager({});
    });

    // Inbox

    $('#cmsInboxLink').click(function() {
        $.modal.close();
        $('#cmsInboxContainer').modal();
        $('#cmsInbox').html(cmsLoadingHTML).cmsInbox({});
    });

    cmsEditorUpdateInbox('');

    // Content Areas

    $('.contentArea').hover(function() {

        var contentArea = $(this);
        $('.cmsContentAreaOptions').each(function() {
            if ($(this).attr('id') != contentArea.attr('id')) {
                $(this).hide(0);
            }
        });

        var areaOptions = $('#cmsContentAreaOptions_' + contentArea.attr('id'));

        if (areaOptions.length > 0) {
            areaOptions.show(0);
        } else {

            areaOptions = $('<div class="cmsContentAreaOptions" id="cmsContentAreaOptions_' + $(this).attr('id') + '"><ul></ul><div class="cmsClear">&nbsp;</div></div>');
            var areaOptionsUL = areaOptions.find('ul:first');

            var optAddModule = $('<li><img src="/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_add_module.png" class="cmsIcon" alt=" " />Add</li>').appendTo(areaOptionsUL);

            optAddModule.click(function() {
                areaOptions.remove();
                $('#cmsAddModuleDialog').remove();
                var cmsAddModuleDialog = $('<div class="cmsModal" id="cmsAddModuleDialog"></div>').appendTo($('body'));
                cmsAddModuleDialog.modal();
                cmsAddModuleDialog.setTemplateURL('/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Templates.CMSAddModuleDialog.tpl');
                $.postJSON('/cms/modules/GetAvailableModules', {}, function(json) {
                    cmsAddModuleDialog.processTemplate(json);

                    cmsAddModuleDialog.find('li').css('cursor', 'pointer').click(function() {
                        $.postJSON('/cms/modules/CreateInstance/' + escape($(this).attr('rel')), {}, function(module) {
                            $.modal.close();
                            var moduleDefinition = $.evalJSON(module.definition);
                            var moduleConfig = $.evalJSON(moduleDefinition.ModuleJSON);
                            var moduleContainer = $('<div></div>').prependTo(contentArea);
                            moduleContainer.html(cmsLoadingHTML);

                            $.post('/cms/modules/Render/' + moduleDefinition.ModuleType, { module: $.base64Encode($.compactJSON(moduleConfig)) }, function(response) {
                                $.get('/CMS/File/AdminScripts?id=-1', {}, function(scripts) {
                                    try { eval(scripts); }
                                    catch (e) { }

                                    moduleContainer.remove();
                                    moduleContainer = $(response);
                                    moduleContainer.attr('id', moduleDefinition.UniqueID).prependTo(contentArea);
                                    moduleContainer.data('config', moduleConfig).data('definition', moduleDefinition);

                                    cmsSetupModule(moduleContainer);
                                    cmsSaveDraft();
                                    $.get('/CMS/File/ModuleStartupScripts?id=-1', {}, function(modulescripts) {
                                        try { eval(modulescripts); }
                                        catch (e) { }
                                    });
                                });
                            });
                        });
                    });
                });
            });

            var optManageModules = $('<li><img src="/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_manage_modules.png" class="cmsIcon" alt=" " />Manage</li>').appendTo(areaOptionsUL);

            optManageModules.click(function() {
                $('#cmsManageModulesDialog').remove();
                var cmsManageModulesDialog = $('<div class="cmsModal" id="cmsManageModulesDialog"></div>').appendTo($('body'));
                cmsManageModulesDialog.modal();
                cmsManageModulesDialog.setTemplateURL('/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Templates.CMSManageModulesDialog.tpl');
                var pageJSON = cmsGetPageJSON();
                cmsManageModulesDialog.processTemplate($.grep(pageJSON.Areas, function(n, i) {
                    return n.Id == $(contentArea).attr('id');
                }));
                cmsManageModulesDialog.find('ul').sortable({ handle: 'span', update: function(event, ui) {
                    var liOrder = 1;
                    cmsManageModulesDialog.find('ul li').each(function() {
                        $('#' + $(this).attr('rel')).attr('order', liOrder);
                        liOrder++;
                    });
                    $(contentArea).find('.cmsModule').tsort({ attr: 'order' });
                }
                });
                cmsManageModulesDialog.find('img.cmsDeleteModule').css('cursor', 'pointer').click(function() {
                    $('#' + $(this).parent().attr('rel')).remove();
                    $(this).parent().remove();
                    cmsSaveDraft();
                });
            });

            var optRefreshModule = $('<li><img src="/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_refresh.png" class="cmsIcon" alt=" " />Refresh</li>').appendTo(areaOptionsUL);

            optRefreshModule.click(function() {
                contentArea.find('.cmsModule').each(function() {
                    cmsUpdateModule(this);
                });
            });

            if (contentArea.css('position') != 'absolute') {
                contentArea.css('position', 'relative');
            }

            $('body').append(areaOptions);
            areaOptions
                .css('width', contentArea.width())
                .css('position', 'absolute')
                .show(0)
                .css('top', parseInt((parseInt(contentArea.offset().top) - parseInt(areaOptions.height()))) + 'px')
                .css('left', parseInt(contentArea.offset().left) + 'px')
                .hover(function() { $(this).show(0); }, function() { $(this).hide(0); })
                .find('li').each(function() {
                    $(this).css('cursor', 'pointer');
                });
        }
    }, function() {
        if (navigator.userAgent.indexOf('MSIE') < 0) {
            $('#cmsContentAreaOptions_' + $(this).attr('id')).hide(0);
        }
    });

    // Find modules, set them up for editing with their relevant jQuery plugin

    $('.cmsModule').each(function() {
        cmsSetupModule(this);
    });

    $('#cmsEditorDummy').animate({
        height: $('#cmsEditorDummy').height()
    }, 250, function() { $('#cmsEditorDummy').height(parseInt(parseInt($('#cmsEditor').height()) * 2) + 'px'); });
});
